const jwt = require('jsonwebtoken');
const { getConnection } = require('../config/database');

const auth = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({ error: '请先登录' });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const connection = await getConnection();
    
    const [users] = await connection.execute(
      'SELECT id, username, email, role, monthly_usage FROM users WHERE id = ?',
      [decoded.userId]
    );

    if (users.length === 0) {
      return res.status(401).json({ error: '用户不存在' });
    }

    req.user = users[0];
    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({ error: '无效的令牌' });
    }
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({ error: '令牌已过期' });
    }
    console.error('认证中间件错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
};

// 检查用户权限
const checkRole = (allowedRoles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ error: '请先登录' });
    }

    if (!allowedRoles.includes(req.user.role)) {
      return res.status(403).json({ error: '权限不足' });
    }

    next();
  };
};

// 检查使用限制
const checkUsageLimit = async (req, res, next) => {
  try {
    const user = req.user;
    const taskType = req.body.taskType || req.query.taskType;
    
    // 免费用户限制
    if (user.role === 'free') {
      const monthlyLimit = taskType === 'image' ? 10 : 1;
      
      if (user.monthly_usage >= monthlyLimit) {
        return res.status(403).json({ 
          error: '已达到本月使用限制，请升级到付费版',
          limit: monthlyLimit,
          current: user.monthly_usage
        });
      }
    }

    next();
  } catch (error) {
    console.error('检查使用限制错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
};

module.exports = {
  auth,
  checkRole,
  checkUsageLimit
}; 